﻿using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.JsonWebTokens;
using Shop.Core.Authorize;
using Shop.Core.Helper;
using Shop.Core.Repository;
using Shop.Core.Share;
using Shop.IServices.Admin;
using Shop.Model.Dto.Admin.Jur;
using Shop.Model.Entity.Jur;
using Shop.Model.View.Admin.Jur;
using Shop.Model.View.Admin.JurUser;

namespace Shop.Services.Admin;

public class AccountService: AbstractService, IAccountService
{
    private readonly RepositoryBase<JurUser> _userRepository;
    private readonly IUserRoleService _userRoleService;
    private readonly PermissionRequirement _permissionRequirement;
    private readonly JwtConfig _jwtConfig;

    
    public AccountService(
        RepositoryBase<JurUser> userRepository
        ,IUserRoleService userRoleService
        ,PermissionRequirement permissionRequirement
        ,IOptions<JwtConfig> jwtConfig)
    {
        _userRepository = userRepository;
        _userRoleService = userRoleService;
        _permissionRequirement = permissionRequirement;
        _jwtConfig = jwtConfig.Value;
    }

    /// <summary>
    /// 管理员登录
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    /// <exception cref="AdminLoginVo"></exception>
    public async Task<AppResult<AdminLoginVo>> AdminLogin(AdminLoginDto dto)
    {
        var useInfo = await _userRepository.Where(x => x.Account == dto.Account).FirstAsync();
        if (useInfo == null)
            return Problem("账号不存在");
        else
        {
            if (useInfo.State == -1)
                return Problem("账号已注销,请联系管理员");
            if (useInfo.State == 1)
                return Problem("账号已冻结,请联系管理员");
            var password = CommonHelper.Md5For32(dto.PassWord);
            if (!password.Equals(useInfo.PassWord))
                return Problem("账号或密码错误");
            var roleIds = await _userRepository.Change<JurUserRole>().AsQueryable()
                .Where(x => x.UserId == useInfo.Id)
                .Select(x => x.RoleId)
                .ToArrayAsync();
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.GivenName, useInfo.Name),
                new Claim(ClaimTypes.Name, useInfo.Account),
                new Claim(JwtRegisteredClaimNames.Jti, useInfo.Id.ToString())
            };
            claims.AddRange(roleIds.Select(s => new Claim(ClaimTypes.Role, s.ToString())));
            var list = await _userRoleService.GetRoleMenu();
            _permissionRequirement.Permissions = list;
            //用户标识
            var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
            identity.AddClaims(claims);
            
            var token = JwtToken.CreateToken(_jwtConfig, claims.ToArray());
            return new AdminLoginVo() { Token = token};
        }
    }

    /// <summary>
    /// 获取管理员信息
    /// </summary>
    /// <param name="uId"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public AppResult<AdminInfoVo> AdminInfo(long uId)
    {
        var data = _userRepository.Where(x => x.Id == uId)
            .Select(x => new AdminInfoVo
            {
                Account = x.Account,
                Head = x.Head,
                Name = x.Name
            }).First();
        return data;
    }
}